package com.zusmart.core.bean.support;

import com.zusmart.core.bean.cause.BeanInstanceCreateException;
import com.zusmart.core.interceptor.InterceptorHandler;
import com.zusmart.core.proxy.ProxyManager;

public class BeanInstanceCreatorForObject extends AbstractBeanInstanceCreator {

	public BeanInstanceCreatorForObject(BeanDefinitionForObject beanDefinition) {
		super(beanDefinition);
	}

	@Override
	public BeanDefinitionForObject getBeanDefinition() {
		return (BeanDefinitionForObject) super.getBeanDefinition();
	}

	@Override
	protected Object doCreateBeanInstance() throws BeanInstanceCreateException {
		try {
			BeanDefinitionForObject beanDefinition = this.getBeanDefinition();
			ProxyManager proxyManager = beanDefinition.getBeanDefinitionRegistry().getProxyManager();
			Object beanInstance = beanDefinition.getTargetBeanInstance();
			InterceptorHandler[] handlers = this.searchInterceptorHandlers(beanDefinition.getBeanClass());
			if (null == beanInstance) {
				throw new BeanInstanceCreateException(String.format("bean target instance must not be null (%s)", beanDefinition));
			}
			if (handlers.length == 0) {
				return beanInstance;
			} else {
				return proxyManager.createProxyByInstance(beanInstance, handlers);
			}
		} catch (Throwable t) {
			throw new BeanInstanceCreateException(t.getMessage(), t);
		}
	}

}